package com.ict.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ict.common.utils.DateUtils;
import com.ict.common.utils.StringUtils;
import com.ict.common.utils.uuid.IdUtils;
import com.ict.web.domain.Performance;
import com.ict.web.domain.PerformanceIndicators;
import com.ict.web.domain.PerformanceRule;
import com.ict.web.domain.ProjectManagement;
import com.ict.web.dto.InsertPerIndicatorsDto;
import com.ict.web.dto.InsertPerformanceDto;
import com.ict.web.dto.QueryPerformanceDto;
import com.ict.web.dto.UpdatePerformanceDto;
import com.ict.web.mapper.PerformanceIndicatorsMapper;
import com.ict.web.mapper.PerformanceMapper;
import com.ict.web.mapper.PerformanceRuleMapper;
import com.ict.web.service.IPerformanceIndicatorsService;
import com.ict.web.service.IPerformanceService;
import com.ict.web.vo.PerIndicatorsVo;
import com.ict.web.vo.PerformanceDetailVo;
import com.ict.web.vo.PerformanceListVo;

import com.ict.web.vo.PerformanceRuleVo;
import com.sun.jna.platform.win32.WinDef;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * 绩效Service业务层处理
 *
 * @author ruoyi
 * @date 2022-02-15
 */
@Service
public class PerformanceServiceImpl extends ServiceImpl<PerformanceMapper, Performance> implements IPerformanceService {
    @Autowired
    private PerformanceMapper performanceMapper;
    @Autowired
    private PerformanceIndicatorsMapper performanceIndicatorsMapper;
    @Autowired
    private PerformanceRuleMapper performanceRuleMapper;
    @Autowired
    private IPerformanceIndicatorsService performanceIndicatorsService;
    @Autowired
    private PerformanceIndicatorsMapper indicatorsMapper;

    /**
     * 查询绩效详情
     *
     * @param perId 绩效主键
     * @return 绩效
     */
    @Override
    public PerformanceDetailVo selectPerformanceByPerId(Long perId) {
      PerformanceDetailVo detailVo =  performanceMapper.selectPerformanceByPerId(perId);
      if (detailVo.getIndicatorsVos() == null){
          List<PerIndicatorsVo> indicatorsVoList = performanceIndicatorsMapper.selectPerformanceIndicatorsListByPerId(perId);
          detailVo.setIndicatorsVos(indicatorsVoList);
          indicatorsVoList.forEach(indicatorsVo -> {
              if (indicatorsVo.getRules() == null) {
                    indicatorsVo.setRules(performanceRuleMapper.selectPerformanceRuleListByIndicatorsId(indicatorsVo.getIndicatorsId()));
              }
          });
          }
      Assert.isTrue(detailVo != null, "绩效不存在!!!");
      return detailVo;
    }

    /**
     * 查询绩效列表
     *
     * @param queryDto 绩效
     * @return 绩效
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<PerformanceListVo> selectPerformanceList(QueryPerformanceDto queryDto) {
        List<PerformanceListVo> performanceList = performanceMapper.selectPerformanceList(queryDto);
        performanceList.forEach(date->{
            if (date.getIndicatorsName() == null){
                List<PerIndicatorsVo> indicatorsList = indicatorsMapper.selectPerformanceIndicatorsListByPerId(date.getPerId());
                List<String>  indicatorsListName = indicatorsList.stream().map(PerIndicatorsVo::getIndicatorsName).collect(Collectors.toList());
                date.setIndicatorsName(indicatorsListName);
            }
        });
        return performanceList;
    }

    /**
     * 新增绩效
     *
     * @param addDto 绩效
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertPerformance(InsertPerformanceDto addDto) {
        List<InsertPerIndicatorsDto> perIndicators = addDto.getPerIndicators();
        double sum = 0D;
        for (InsertPerIndicatorsDto dto : perIndicators){
            sum = sum+dto.getIndicatorsWeight();
        }
        Assert.isTrue(sum==1D,"权重总值未到100%");

        Performance performance = InsertPerformanceDto.of(addDto);
        //加入绩效指标
        performanceIndicatorsService.insertPerformanceIndicators(performance.getPerId(), addDto.getPerIndicators());
        performanceMapper.insert(performance);
        return String.valueOf(performance.getPerId());
    }

    /**
     * 修改绩效
     *
     * @param updateDto 绩效
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePerformance(Long perId,UpdatePerformanceDto updateDto) {
        List<InsertPerIndicatorsDto> insertPerIndicatorsDtoS = updateDto.getInsertPerIndicatorsDtoS();
        double sum = 0D;
        for (InsertPerIndicatorsDto dto : insertPerIndicatorsDtoS){
            sum = sum+dto.getIndicatorsWeight();
        }
        Assert.isTrue(sum==1D,"权重总值未到100%");

        Performance performance = UpdatePerformanceDto.of(updateDto);
        Performance bean = this.getById(perId);
        Assert.isTrue(bean != null && !(bean.getDelFlag().equals(Performance.DELETE_STATUS_UNNORMAL)),
                "绩效配置不存在!!!");
        Assert.isTrue(bean.getPreStatus().equals(Performance.PER_STATUS_NotENABLE), "配置在使用中或停止使用，不能编辑!!!");
        //删除指标规则
        QueryWrapper<PerformanceIndicators> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("per_id",perId);
        queryWrapper.eq("del_flag",PerformanceIndicators.DELETE_STATUS_NORMAL);
        List<PerformanceIndicators> indicatorsList = performanceIndicatorsMapper.selectList(queryWrapper);
        indicatorsList.forEach(data ->{
            QueryWrapper<PerformanceRule>  queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("indicators_id",data.getIndicatorsId());
            int resultRule = performanceRuleMapper.delete(queryWrapper1);
            Assert.isTrue(resultRule > 0,"指标规则删除失败!!!");
        });
        //删除绩效指标
        int resultPerformanceIndicators = performanceIndicatorsMapper.delete(queryWrapper);
        System.err.println(resultPerformanceIndicators);
        Assert.isTrue(resultPerformanceIndicators > 0,"绩效指标删除失败!!!");

        //删除绩效
        int result =  performanceMapper.deleteById(perId);
        Assert.isTrue(result >0 ,"绩效删除失败!!!");

        performanceIndicatorsService.insertPerformanceIndicators(performance.getPerId(),updateDto.getInsertPerIndicatorsDtoS());
        performanceMapper.insert(performance);
    }

    /**
     * 绩效配置启用
     *
     * @param perId
     */
    @Override
    public void enable(Long perId) {
        Performance bean = this.getById(perId);
        Assert.isTrue(bean != null && bean.getDelFlag().equals(Performance.DELETE_STATUS_NORMAL), "绩效配置不存在!!!");
        Assert.isTrue(bean.getPreStatus().equals(Performance.PER_STATUS_NotENABLE),"绩效配置在使用中或停用,无法启用!!!");
        QueryWrapper<Performance> performanceQueryWrapper = new QueryWrapper<>();
        performanceQueryWrapper.eq("pre_status",Performance.PER_STATUS_USING);
        performanceQueryWrapper.eq("range_application",bean.getRangeApplication());
        performanceQueryWrapper.eq("del_flag",Performance.DELETE_STATUS_NORMAL);
        List<Performance> performanceList = performanceMapper.selectList(performanceQueryWrapper);
        Assert.isTrue(performanceList.size() < 1,"当前类型的绩效只能启用一个，如果需要关闭已启用的绩效!!!");
        bean.setPreStatus(Performance.PER_STATUS_USING);
        bean.setUpdateTime(DateUtils.getNowDate());
        this.updateById(bean);
    }

    /**
     * 绩效配置停用
     *
     * @param perId
     */
    @Override
    public void disContinue(Long perId) {
        Performance bean = this.getById(perId);
        Assert.isTrue(bean != null && bean.getDelFlag().equals(Performance.DELETE_STATUS_NORMAL), "绩效配置不存在!!!");
        bean.setPreStatus(Performance.PER_STATUS_DISCONTINUE);
        bean.setUpdateTime(DateUtils.getNowDate());
        this.updateById(bean);
    }

    /**
     * 删除绩效信息
     *
     * @param perId 绩效主键
     * @return 结果
     */
    @Override
    public int deletePerformanceByPerId(Long perId) {
        Performance bean = this.getById(perId);
        Assert.isTrue(!bean.getPreStatus().equals(Performance.PER_STATUS_USING), "绩效使用中，不能删除!!!");
        return performanceMapper.deletePerformanceByPerId(perId);
    }

    @Override
    public List<PerformanceIndicators> selectValidPerformanceRule() {
        List<Performance> performances =
                performanceMapper.selectList(Wrappers.<Performance>lambdaQuery().eq(Performance::getPreStatus,
                        Performance.PER_STATUS_USING).orderByAsc(Performance::getPerId));
        List<PerformanceIndicators> indicatorsList = new ArrayList<>();
        performances.forEach(data->{
            if (data.getRangeApplication().equals("1")){
                LambdaQueryWrapper<PerformanceIndicators> performanceIndicatorsLambdaQueryWrapper =
                        Wrappers.<PerformanceIndicators>lambdaQuery().eq(PerformanceIndicators::getPerId,
                                data.getPerId()).orderByAsc(PerformanceIndicators::getPerId);

                List<PerformanceIndicators> performanceIndicators =
                        performanceIndicatorsMapper.selectList(performanceIndicatorsLambdaQueryWrapper);
                Assert.isTrue(!CollectionUtils.isEmpty(performanceIndicators),"绩效指标为空!!!");

                for (PerformanceIndicators performanceIndicator : performanceIndicators) {
                    LambdaQueryWrapper<PerformanceRule> performanceRuleLambdaQueryWrapper =
                            Wrappers.<PerformanceRule>lambdaQuery().eq(PerformanceRule::getIndicatorsId,
                                    performanceIndicator.getIndicatorsId());
                    List<PerformanceRule> performanceRules =
                            performanceRuleMapper.selectList(performanceRuleLambdaQueryWrapper);
                    performanceIndicator.setPerformanceRuleList(performanceRules);
                    indicatorsList.add(performanceIndicator);
                }

            }else if (data.getRangeApplication().equals("1")){
                LambdaQueryWrapper<PerformanceIndicators> performanceIndicatorsLambdaQueryWrapper =
                        Wrappers.<PerformanceIndicators>lambdaQuery().eq(PerformanceIndicators::getPerId,
                                data.getPerId()).orderByAsc(PerformanceIndicators::getPerId);

                List<PerformanceIndicators> performanceIndicators =
                        performanceIndicatorsMapper.selectList(performanceIndicatorsLambdaQueryWrapper);
                Assert.isTrue(!CollectionUtils.isEmpty(performanceIndicators),"绩效指标为空!!!");

                for (PerformanceIndicators performanceIndicator : performanceIndicators) {
                    LambdaQueryWrapper<PerformanceRule> performanceRuleLambdaQueryWrapper =
                            Wrappers.<PerformanceRule>lambdaQuery().eq(PerformanceRule::getIndicatorsId,
                                    performanceIndicator.getIndicatorsId());
                    List<PerformanceRule> performanceRules =
                            performanceRuleMapper.selectList(performanceRuleLambdaQueryWrapper);
                    performanceIndicator.setPerformanceRuleList(performanceRules);
                    indicatorsList.add(performanceIndicator);
                }
            }

        });
        return indicatorsList;
    }

}
